package summer.codegenerator.persistence.hibernate.base.tool;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jiangz
 * @birth  2017年12月5日 下午10:41:01
 */
public class ConditionGroup implements Serializable,WhereClause {

	private static final long serialVersionUID = 1L;

	private List<Condition> conditions;

	private String logic;

	public boolean useless() {
		return conditions == null || conditions.size() == 0;
	}

	public int size() {
		return conditions.size();
	}

	@Override
	public String toString() {
		if (conditions == null || conditions.size() == 0) {
			return "";
		} else if (conditions.size() == 1) {
			return conditions.get(0).toString();
		} else {
			StringBuilder clause = new StringBuilder();
			clause.append("(");
			int len = conditions.size();
			for (int i = 0; i < len - 1; i++) {
				Condition condition = conditions.get(i);
				clause.append(String.format("%s %s ", condition.toString(), this.logic));
			}
			Condition condition = conditions.get(len - 1);
			clause.append(condition.toString());
			clause.append(")");
			return clause.toString();
		}
	}

	@Override
	public String getClause() {
		if (conditions == null || conditions.size() == 0) {
			return "";
		} else {
			StringBuilder clause = new StringBuilder();
			clause.append(" where ");
			int len = conditions.size();
			for (int i = 0; i < len - 1; i++) {
				Condition condition = conditions.get(i);
				clause.append(String.format("%s %s ", condition.toString(), this.logic));
			}
			Condition condition = conditions.get(len - 1);
			clause.append(condition.toString());
			return clause.toString();
		}
	}
	
	@Override
	public Map<String, Object> getParamMap() {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		for(Condition condition : this.conditions) {
			paramMap.putAll(condition.getParamMap());
		}
		return paramMap;
	}

	public ConditionGroup() {
		this.conditions = new ArrayList<Condition>();
		this.logic = "or";
	}

	public ConditionGroup(String logic, Condition... conditions) {
		this.logic = logic;
		this.conditions = new ArrayList<Condition>();
		for (Condition condition : conditions) {
			this.conditions.add(condition);
		}
	}

	public ConditionGroup(List<Condition> conditions, String logic) {
		this.conditions = conditions;
		this.logic = logic;
	}

	public List<Condition> getConditions() {
		return conditions;
	}

	public void setConditions(List<Condition> conditions) {
		this.conditions = conditions;
	}

	public String getLogic() {
		return logic;
	}

	public void setLogic(String logic) {
		this.logic = logic;
	}

}
